package com.tools.web.filter.gateway;

import com.tools.common.object.Note;

/**
 * 使用 Redis 实现网关过滤器的 Lua 脚本接口
 * */
@Note("使用 Redis 实现网关过滤器的 Lua 脚本接口")
public interface GatewayRedisLuaScript {

    String HAS =
            "local key = KEYS[1]" +
            "local value = redis.call('GET', key)" +
            "local expiration = ARGV[1]" +
            "if not value then" +
            "   redis.call('SETEX', key, expiration, 1)" +
            "   return 1" +
            "end" +
            "local requestCount = tonumber(value)" +
            "local allow = tonumber(ARGV[2])" +
            "if requestCount < allow then" +
            "   local ttl = redis.call('TTL', key)" +
            "   if ttl <= 0 then" +
            "       redis.call('SETEX', key, expiration, 1)" +
            "       return 1" +
            "   else" +
            "       redis.call('SETEX', key, ttl, requestCount + 1)" +
            "       return 1" +
            "   end" +
            "else" +
            "   return 0" +
            "end";
}
